const http = require('http');

console.log('📊 测试统计API功能...\n');

// 测试统计API
function testStatsAPI(endpoint, name) {
  return new Promise((resolve, reject) => {
    const options = {
      hostname: 'localhost',
      port: 5000,
      path: `/api/stats${endpoint}`,
      method: 'GET'
    };
    
    console.log(`📝 测试: ${name}`);
    console.log(`🔗 GET ${options.path}`);
    
    const req = http.request(options, (res) => {
      let body = '';
      
      res.on('data', (chunk) => {
        body += chunk;
      });
      
      res.on('end', () => {
        try {
          const response = JSON.parse(body);
          console.log(`📊 状态码: ${res.statusCode}`);
          
          if (response.success) {
            console.log('✅ API调用成功');
            console.log('📄 数据预览:', JSON.stringify(response.data, null, 2).substring(0, 200) + '...');
          } else {
            console.log('❌ API调用失败:', response.error);
          }
          
          resolve({ success: response.success, data: response.data });
        } catch (error) {
          console.log('❌ JSON解析失败:', error.message);
          console.log('📄 原始响应:', body.substring(0, 200));
          resolve({ success: false, error: 'JSON解析失败' });
        }
      });
    });
    
    req.on('error', (error) => {
      console.log('❌ 请求失败:', error.message);
      reject(error);
    });
    
    req.end();
  });
}

// 运行所有统计API测试
async function runStatsTests() {
  const tests = [
    { endpoint: '/overview', name: '统计概览' },
    { endpoint: '/category-distribution', name: '分类分布' },
    { endpoint: '/priority-distribution', name: '优先级分布' },
    { endpoint: '/time-trends?days=7', name: '7天时间趋势' },
    { endpoint: '/time-trends?days=30', name: '30天时间趋势' },
    { endpoint: '/efficiency', name: '效率分析' },
    { endpoint: '/tag-usage', name: '标签使用统计' }
  ];
  
  console.log('🚀 开始统计API测试...\n');
  
  for (const test of tests) {
    try {
      await testStatsAPI(test.endpoint, test.name);
      console.log('─'.repeat(60));
      
      // 等待一下避免请求过快
      await new Promise(resolve => setTimeout(resolve, 500));
    } catch (error) {
      console.log(`❌ 测试 "${test.name}" 失败:`, error.message);
      console.log('─'.repeat(60));
    }
  }
  
  console.log('\n🎉 统计API测试完成!');
}

// 启动测试
runStatsTests();
